package com.cardbaobao.cardbabyclient.ui.activity;

import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.AuthStateUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.CreditToMoneyInfo;
import com.cardbaobao.cardbabyclient.utils.AnimationUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by jiangzx on 2017/3/30.
 * 信用变钱
 */

public class CreditToMoneyActivity extends BaseActivity {
    private static final int COLOR_BLUE=0xff6cc2ff;
    private static final int COLOR_GRAY=0xffafafaf;
    private static final String TYPE_CHSI="XUEXIN";//学信
    private static final String TYPE_OPERATOR="YYS";//运营商

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.tv_quota)
    TextView tvQuota;//预估额度

    @BindView(R.id.tv_to_crash)
    TextView tvToCrash;//去变现

    @BindView(R.id.progressbar)
    ProgressBar progressBar;//完成进度

    @BindView(R.id.tv_progress)
    TextView tvProgress;//完成进度文本显示

    @BindView(R.id.iv_identity_characteristics)
    ImageView ivIdentityCharacteristics;//身份特质向下/上箭头

    @BindView(R.id.ll_identity_characteristics_container)
    LinearLayout llIdentityCharacteristicsContainer;//身份特质布局容器

    @BindView(R.id.iv_performance_ability)
    ImageView ivPerformanceAbility;//履约能力向下/上箭头

    @BindView(R.id.ll_performance_ability_container)
    LinearLayout llPerformanceAbilityContainer;//履约能力布局容器


    @BindView(R.id.iv_relationship)
    ImageView ivRelationship;//人脉关系向下/上箭头

    @BindView(R.id.ll_relationship_container)
    LinearLayout llRelationshipContainer;

    @BindView(R.id.tv_certification_status)
    TextView tvCertificationStatus;

    @BindView(R.id.tv_personal_info_status)
    TextView tvPersonalInfoStatus;

    @BindView(R.id.tv_chsi_status)
    TextView tvChsiStatus;//学信网

    @BindView(R.id.tv_provident_fund_status)
    TextView tvProvidentFundStatus;//公积金

    @BindView(R.id.tv_social_security_status)
    TextView tvSocialSecurityStatus;//社保

    @BindView(R.id.tv_operator_status)
    TextView tvOperatorStatus;//运营商

    private CreditToMoneyInfo info;
    private Dialog tipDialog;

    private int quota;//额度 往贷款页面跳转时所携带的金额
    private String codes;//往贷款页面跳转时携带的授权code
    private String authTypeName;//往贷款页面跳转时携带的授权名称
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCurrentPageId= Self.Page.app_credit_to_money_page;

        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTips();
            }
        });
        ivIdentityCharacteristics.setTag(0);
        ivPerformanceAbility.setTag(0);
        ivRelationship.setTag(0);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_credit_to_money;
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x00e));
        GoogleAnalyticsUtil.setScreenName(Google.CREDIT_MONEY);
    }

    @OnClick({R.id.tv_to_crash,
            R.id.rl_certification,
            R.id.rl_personal_info,
            R.id.rl_chsi,
            R.id.rl_social_security,
            R.id.rl_provident_fund,
            R.id.ll_identity_characteristics,
            R.id.ll_performance_ability,
            R.id.ll_relationship,
            R.id.rl_operator})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.tv_to_crash:
                if(quota>0){
                    initIntent();
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_to_loan,
                            Self.Action.app_click_credit_to_money_to_loan_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    mIntent.setClass(mContext, LoanFilterActivity.class);
                    mIntent.putExtra(LoanFilterActivity.LOAN_TYPE_AUTH_REPAYMENT_CODE_S,codes);
                    mIntent.putExtra(LoanFilterActivity.LOAN_TYPE_AUTH_REPAYMENT_NAME_S,authTypeName);
                    mIntent.putExtra(LoanFilterActivity.LOAN_FILTER_AMOUNT_I,quota);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(mIntent);
                }else{
                    ToastUtil.showToast("请实名认证后再操作");
                }
                break;
            case R.id.rl_certification:
                //实名认证
                if(info!=null){
                    //是否已验证 1已验证 0未验证
                    initIntent();
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_identify_verify,
                            Self.Action.app_click_credit_to_money_identify_verify_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    if(info.getAttestation()==1){
                        mIntent.setClass(mContext, RealNamePassActivity.class);
                    }else{
                        mIntent.setClass(mContext, RealNameAuthenticationActivity.class);
                        mIntent.putExtra(RealNameAuthenticationActivity.GO_RESULT_ACTIVITY_B,true);
                    }
                    startActivity(mIntent);
                }
                break;
            case R.id.rl_chsi:
                //学信网
                SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_chsi_auth,
                        Self.Action.app_click_credit_to_money_chsi_auth_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                toChsiAuthActivity();
                break;
            case R.id.rl_personal_info:
                //个人信息
                SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_personal_material,
                        Self.Action.app_click_credit_to_money_personal_material_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                toPersonalInfoActivity();
                break;
            case R.id.rl_social_security:
                //社保
                SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_social_security_auth,
                        Self.Action.app_click_credit_to_money_social_security_auth_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                toAuthorizationActivity(AuthorizationActivity.TYPE_SHE_BAO);
                break;
            case R.id.rl_provident_fund:
                //公积金
                SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_provident_fund_auth,
                        Self.Action.app_click_credit_to_money_provident_fund_auth_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                toAuthorizationActivity(AuthorizationActivity.TYPE_GJJ);
                break;
            case R.id.ll_identity_characteristics:
                if(((int)ivIdentityCharacteristics.getTag())==0){
                    ivIdentityCharacteristics.setTag(1);
                    ivIdentityCharacteristics.setImageResource(R.mipmap.icon_up_gray);
                    AnimationUtil.visibleAnimator(llIdentityCharacteristicsContainer);
                }else{
                    ivIdentityCharacteristics.setTag(0);
                    ivIdentityCharacteristics.setImageResource(R.mipmap.icon_down_gray);
                    AnimationUtil.invisibleAnimator(llIdentityCharacteristicsContainer);
                }
                break;
            case R.id.ll_performance_ability:
                if(((int)ivPerformanceAbility.getTag())==0){
                    ivPerformanceAbility.setTag(1);
                    ivPerformanceAbility.setImageResource(R.mipmap.icon_up_gray);
                    AnimationUtil.visibleAnimator(llPerformanceAbilityContainer);
                }else{
                    ivPerformanceAbility.setTag(0);
                    ivPerformanceAbility.setImageResource(R.mipmap.icon_down_gray);
                    AnimationUtil.invisibleAnimator(llPerformanceAbilityContainer);
                }
                break;
            case R.id.ll_relationship:
                if(((int)ivRelationship.getTag())==0){
                    ivRelationship.setTag(1);
                    ivRelationship.setImageResource(R.mipmap.icon_up_gray);
                    AnimationUtil.visibleAnimator(llRelationshipContainer);
                }else{
                    ivRelationship.setTag(0);
                    ivRelationship.setImageResource(R.mipmap.icon_down_gray);
                    AnimationUtil.invisibleAnimator(llRelationshipContainer);
                }
                break;
            case R.id.rl_operator:
                //运营商授权
                SelfUtils.buriedClickData(Self.Action.app_click_credit_to_money_operator_auth,
                        Self.Action.app_click_credit_to_money_operator_auth_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                toOperatorActivity();
                break;
        }
    }

    /**去往学信网授权页面*/
    private void toChsiAuthActivity(){
        if(info!=null){
            if(info.getAttestation()==1){
                String text=tvChsiStatus.getText().toString().trim();
                if(AuthStateUtils.canEnterAuth(text)){
                    initIntent();
                    mIntent.setClass(mContext,ChsiAuthActivity.class);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(mIntent);
                }else{
                    ToastUtil.showToast(text);
                }
            }else{
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.need_real_name_verified));
            }
        }
    }

    /**去个人信息页面*/
    private void toPersonalInfoActivity(){
        if(info!=null){
            if(info.getAttestation()==1){
                initIntent();
                mIntent.setClass(mContext, PersonMaterialActivity.class);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);
            }else{
                //未实名验证
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.need_real_name_verified));
            }
        }
    }

    /**去到社保、公积金授权页面
     *@param type GJJ SHE_BAO
     */
    private void toAuthorizationActivity(String type){
        if(info!=null){
            if(info.getAttestation()==1){
                //已实名认证
                if(AuthorizationActivity.TYPE_SHE_BAO.equals(type)){
                    //已授权后不能再次授权
                    String text=tvSocialSecurityStatus.getText().toString().trim();
                    if(AuthStateUtils.canEnterAuth(text)){
                        initIntent();
                        mIntent.putExtra(AuthorizationActivity.TYPE_AUTHORIZATION_S,type);
                        mIntent.setClass(mContext, AuthorizationActivity.class);
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }else{
                        ToastUtil.showToast(text);
                    }
                }else if(AuthorizationActivity.TYPE_GJJ.equals(type)){
                    String text=tvProvidentFundStatus.getText().toString().trim();
                    if(AuthStateUtils.canEnterAuth(text)){
                        initIntent();
                        mIntent.putExtra(AuthorizationActivity.TYPE_AUTHORIZATION_S,type);
                        mIntent.setClass(mContext, AuthorizationActivity.class);
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }else{
                        ToastUtil.showToast(text);
                    }
                }
            }else{
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.need_real_name_verified));
            }
        }
    }

    /**去到运营商授权页面*/
    private void toOperatorActivity(){
        if(info!=null){
            if(info.getAttestation()==1){
                //已实名认证
                String text=tvOperatorStatus.getText().toString().trim();
                if(AuthStateUtils.canEnterAuth(text)){
                    initIntent();
                    mIntent.setClass(mContext, OperatorAuthActivity.class);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(mIntent);
                }else{
                    ToastUtil.showToast(text);
                }
            }else{
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.need_real_name_verified));
            }
        }
    }

    private void showTips(){
        if(null!=info){
            if(null== tipDialog){
                tipDialog=new Dialog(mContext,R.style.dialog);
                View view= LayoutInflater.from(mContext).inflate(R.layout.dialog_credit_crash_tip,null);
                view.findViewById(R.id.bt_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tipDialog.dismiss();
                    }
                });
                tipDialog.setContentView(view);
                tipDialog.setCanceledOnTouchOutside(false);
                Drawable drawable=ContextCompat.getDrawable(mContext,R.mipmap.img_credit_crash_tip);
                int height=drawable.getIntrinsicHeight();
                int width=drawable.getIntrinsicWidth();
                ((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable);
                Window window=tipDialog.getWindow();
                if(window!=null){
                    WindowManager.LayoutParams params=window.getAttributes();
                    params.width=width;
                    params.height=height;
                    params.gravity=Gravity.CENTER;
                    window.setAttributes(params);
                }
            }
            tipDialog.show();
        }
    }

    private void loadData(){
        showProgressDialog(false);
        Observable<String> observable=
                Api.getCreditToCashIndex(String.valueOf(mApplication.getUser().getID()));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                JSONObject json=JSON.parseObject(s).getJSONObject("data");
                info=JSON.parseObject(json.toJSONString(),CreditToMoneyInfo.class);
                if(info!=null){
                    if (info.getAttestation() == 1) {
                        //已实名认证
                        tvCertificationStatus.setText("已认证");
                        tvCertificationStatus.setTextColor(COLOR_BLUE);
                    } else {
                        tvCertificationStatus.setText("未认证");
                        tvCertificationStatus.setTextColor(COLOR_GRAY);
                    }
                    if (info.getWrite() == 1) {
                        //已填写个人信息
                        tvPersonalInfoStatus.setText("已填写");
                        tvPersonalInfoStatus.setTextColor(COLOR_BLUE);
                    } else {
                        tvPersonalInfoStatus.setText("未填写");
                        tvPersonalInfoStatus.setTextColor(COLOR_GRAY);
                    }
                    loadAuthorizationInfo();
                }
            }
        });
    }

    ///获取授权信息
    private void loadAuthorizationInfo(){
        Observable<String> observable=Api.getAuthStatus(mApplication.getUser().getID());
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                int item = 0;
                quota=0;
                codes="";
                StringBuilder sb=new StringBuilder();
                List<String> names=new ArrayList<>();
                JSONArray array = JSON.parseArray(s);
                if (array != null ) {
                    if(array.size() > 0){
                        JSONObject object;
                        for (int i = 0, size = array.size(); i < size; i++) {
                            object = array.getJSONObject(i);
                            //先拿授权状态
                            int state=object.getIntValue("state");//0授权中 1已授权
                            String channel=object.getString("channel_type");
                            if(state==0){
                                if(AuthorizationActivity.TYPE_SHE_BAO.equals(channel)){
                                    tvSocialSecurityStatus.setText(AuthStateUtils.AUTH_STATE_AUTH_ING);
                                    tvSocialSecurityStatus.setTextColor(COLOR_BLUE);
                                }else if(AuthorizationActivity.TYPE_GJJ.equals(channel)){
                                    tvProvidentFundStatus.setText(AuthStateUtils.AUTH_STATE_AUTH_ING);
                                    tvProvidentFundStatus.setTextColor(COLOR_BLUE);
                                }else if(TYPE_CHSI.equals(channel)){
                                    tvChsiStatus.setText(AuthStateUtils.AUTH_STATE_AUTH_ING);
                                    tvChsiStatus.setTextColor(COLOR_BLUE);
                                }else if(TYPE_OPERATOR.equals(channel)){
                                    tvOperatorStatus.setText(AuthStateUtils.AUTH_STATE_AUTH_ING);
                                    tvOperatorStatus.setTextColor(COLOR_BLUE);
                                }
                            }else if(state==1){
                                //判断授权是否过期
                                long taskTime = object.getLong("update_time");
                                long current = object.getLong("current_time");
                                boolean flag = false;
                                if (current - taskTime >= 1000 * 60 * 60 * 24 * 90L) {
                                    //授权过期
                                    flag = true;
                                } else {
                                    item++;
                                }
                                if (AuthorizationActivity.TYPE_SHE_BAO.equals(channel)) {
                                    if (flag) {
                                        tvSocialSecurityStatus.setText(AuthStateUtils.AUTH_STATE_EXPIRED);
                                        tvSocialSecurityStatus.setTextColor(COLOR_GRAY);
                                    } else {
                                        tvSocialSecurityStatus.setText(AuthStateUtils.AUTH_STATE_AUTHORIZED);
                                        tvSocialSecurityStatus.setTextColor(COLOR_BLUE);
                                        quota+=3000;
                                        sb.append(Constant.SOCIAL_SECURITY_CODE);
                                        sb.append(",");
                                        names.add("社保");
                                    }
                                } else if (AuthorizationActivity.TYPE_GJJ.equals(channel)) {
                                    if (flag) {
                                        tvProvidentFundStatus.setText(AuthStateUtils.AUTH_STATE_EXPIRED);
                                        tvProvidentFundStatus.setTextColor(COLOR_GRAY);
                                    } else {
                                        tvProvidentFundStatus.setText(AuthStateUtils.AUTH_STATE_AUTHORIZED);
                                        tvProvidentFundStatus.setTextColor(COLOR_BLUE);
                                        quota+=5000;
                                        sb.append(Constant.PROVIDENT_FUND_CODE);
                                        sb.append(",");
                                        names.add("公积金");
                                    }
                                }else if(TYPE_CHSI.equals(channel)){
                                    if(flag){
                                        tvChsiStatus.setText(AuthStateUtils.AUTH_STATE_EXPIRED);
                                        tvChsiStatus.setTextColor(COLOR_GRAY);
                                    }else{
                                        tvChsiStatus.setText(AuthStateUtils.AUTH_STATE_AUTHORIZED);
                                        tvChsiStatus.setTextColor(COLOR_BLUE);
                                        quota+=3000;
                                        sb.append(Constant.CHSI_CODE);
                                        sb.append(",");
                                        names.add("学信网");
                                    }
                                }else if(TYPE_OPERATOR.equals(channel)){
                                    if(flag){
                                        tvOperatorStatus.setText(AuthStateUtils.AUTH_STATE_EXPIRED);
                                        tvOperatorStatus.setTextColor(COLOR_GRAY);
                                    }else {
                                        tvOperatorStatus.setText(AuthStateUtils.AUTH_STATE_AUTHORIZED);
                                        tvOperatorStatus.setTextColor(COLOR_BLUE);
                                        quota+=1000;
                                        sb.append(Constant.OPERATOR_CODE);
                                        sb.append(",");
                                        names.add("运营商");
                                    }
                                }
                            }else if(state==2){
                                if(AuthorizationActivity.TYPE_SHE_BAO.equals(channel)){
                                    tvSocialSecurityStatus.setText(AuthStateUtils.AUTH_STATE_FAILURE);
                                    tvSocialSecurityStatus.setTextColor(COLOR_GRAY);
                                }else if(AuthorizationActivity.TYPE_GJJ.equals(channel)){
                                    tvProvidentFundStatus.setText(AuthStateUtils.AUTH_STATE_FAILURE);
                                    tvProvidentFundStatus.setTextColor(COLOR_GRAY);
                                }else if(TYPE_CHSI.equals(channel)){
                                    tvChsiStatus.setText(AuthStateUtils.AUTH_STATE_FAILURE);
                                    tvChsiStatus.setTextColor(COLOR_GRAY);
                                }else if(TYPE_OPERATOR.equals(channel)){
                                    tvOperatorStatus.setText(AuthStateUtils.AUTH_STATE_FAILURE);
                                    tvOperatorStatus.setTextColor(COLOR_GRAY);
                                }
                            }
                        }
                    }
                }
                if (info != null) {
                    if (info.getAttestation() == 1) {
                        //已实名认证
                        item++;
                        quota+=1000;
                        sb.append(Constant.IDENTITY_CODE);
                        sb.append(",");
                        names.add("身份证");
                    }
                    if (info.getWrite() == 1) {
                        //已填写个人信息
                        item++;
                    }
                    int progress = item*17;
                    if (progress > 0) {
                        ObjectAnimator animator = ObjectAnimator.
                                ofInt(progressBar, "progress", 0, progress);
                        animator.setInterpolator(new AccelerateDecelerateInterpolator());
                        animator.setDuration(2000);
                        animator.start();
                        if(progress>100){
                            progress=100;
                        }
                        progressBar.setProgress(progress);
                        tvProgress.setText("资料完整度: "+progress + "%");
                    }
                    if(quota>0){
                        tvQuota.setText(String.valueOf(quota));
                        tvToCrash.setVisibility(View.VISIBLE);
                    }else{
                        tvQuota.setText("0.00");
                        tvToCrash.setVisibility(View.INVISIBLE);
                    }
                    int commaIndex=sb.lastIndexOf(",");
                    if(commaIndex!=-1){
                        sb.deleteCharAt(commaIndex);
                    }
                    codes=sb.toString();
                    if(names.size()==1){
                        authTypeName=names.get(0);
                    }
                }
            }
        });
    }
}
